package com.seuic.hnapps.util;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;

public class ServiceCommon {

	public static String appendZero(int k, int length) {
		String str = String.valueOf(k);
		return appendZero(str,length);
	}
	public static String appendZero(long k, int length) {
		String str = String.valueOf(k);
		return appendZero(str,length);
	}
	public static String appendZero(String str, int length) {
		while (str.length() < length) {
			str = "0" + str;
		}
		return str;
	}
	/**
	 * 金额转化
	 * 解决double数据类型运算不准确
	 * str:金额
	 * k: 要进行运算的数
	 * flag:1 加；2 减；3 乘；4 除
	 * fm:返回的数据格式；默认带2位小数
	 */
	public static String multiply(int str, int k, int flag, String fm) {

		BigDecimal a = BigDecimal.valueOf(str);
		BigDecimal b=BigDecimal.valueOf(k);
		String bal = multiply(a,b,flag,fm);

		return bal;
	}
	public static String multiply(String str, int k, int flag, String fm) {

		BigDecimal a = new BigDecimal(str);
		BigDecimal b=BigDecimal.valueOf(k);
		String bal = multiply(a,b,flag,fm);

		return bal;
	}
	public static String multiply(String str, String k, int flag, String fm) {

		BigDecimal a = new BigDecimal(str);
		BigDecimal b= new BigDecimal(k);
		String bal = multiply(a,b,flag,fm);

		return bal;
	}
	public static String multiply(BigDecimal a, BigDecimal b, int flag, String fm) {

		double d = 0;
		if(flag == 4){
			d = a.divide(b).doubleValue();
		}else if(flag == 3){
			d = a.multiply(b).doubleValue();
		}else if(flag == 2){
			d = a.subtract(b).doubleValue();
		}else if(flag == 1){
			d = a.add(b).doubleValue();
		}
		String fma = "";
		if(fm == null || "".equals(fm)){
			fma = "#0.00";
		}else{
			fma = fm;
		}
		DecimalFormat f = new DecimalFormat(fma);
		String bal = f.format(d);
		return bal;
	}

	public static String GBKsubstring(String in, int start, int len){

		try {
			byte[] b = in.getBytes("GBK");
			byte[] o = new byte[len];
			System.arraycopy(b, start, o, 0, len);
			return new String(o,"GBK");
		} catch (UnsupportedEncodingException e) {

		}

		return "";

	}

}
